/*******************************************************************************
 * Copyright (c) 2007 - 2025 Maxprograms.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 1.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/org/documents/epl-v10.html
 *
 * Contributors:
 *     Maxprograms - initial API and implementation
 *******************************************************************************/

interface ExtractedTerm {
    source: string;
    target: string;
    context: string;
    confidence?: number;
}

interface TermExtractionData {
    projectId: string;
    projectName: string;
    srcLang: string;
    tgtLang: string;
}

class TermExtraction {
    electron = require('electron');

    projectId!: string;
    projectName!: string;
    srcLang!: string;
    tgtLang!: string;
    glossaries: any[] = [];
    
    // UI elements
    projectNameSpan!: HTMLSpanElement;
    languagePairSpan!: HTMLSpanElement;
    glossarySelect!: HTMLSelectElement;
    progressContainer!: HTMLDivElement;
    progressFill!: HTMLDivElement;
    progressText!: HTMLSpanElement;
    currentSegmentDiv!: HTMLDivElement;
    termsList!: HTMLDivElement;
    termCount!: HTMLSpanElement;
    noTermsMessage!: HTMLDivElement;
    addingProgress!: HTMLDivElement;
    addingProgressText!: HTMLDivElement;
    addingProgressFill!: HTMLDivElement;
    
    startBtn!: HTMLButtonElement;
    stopBtn!: HTMLButtonElement;
    selectAllBtn!: HTMLButtonElement;
    addSelectedBtn!: HTMLButtonElement;

    extractedTerms: ExtractedTerm[] = [];
    isExtracting: boolean = false;
    extractionCancelled: boolean = false;

    constructor() {
        console.log('术语抽取窗口构造函数开始执行');
        
        // 监听主进程主动发送的数据
        this.electron.ipcRenderer.on('term-extraction-data', (event: any, data: TermExtractionData) => {
            console.log('术语抽取窗口收到数据:', data);
            this.setData(data);
            // 项目数据加载后，请求术语库列表
            this.loadGlossaries();
        });

        // 监听术语库数据
        this.electron.ipcRenderer.on('set-term-extraction-glossaries', (event: any, glossaries: any[]) => {
            console.log('术语抽取窗口收到术语库列表:', glossaries);
            this.setGlossaries(glossaries);
        });

        this.electron.ipcRenderer.on('set-theme', (event: any, css: string) => {
            (document.getElementById('theme') as HTMLLinkElement).href = css;
        });

        this.electron.ipcRenderer.send('get-theme');

        console.log('开始初始化UI');
        this.initializeUI();
        
        console.log('术语抽取窗口构造函数执行完成');
    }

    initializeUI(): void {
        this.projectNameSpan = document.getElementById('projectName') as HTMLSpanElement;
        this.languagePairSpan = document.getElementById('languagePair') as HTMLSpanElement;
        this.glossarySelect = document.getElementById('glossarySelect') as HTMLSelectElement;
        this.progressContainer = document.getElementById('progressContainer') as HTMLDivElement;
        this.progressFill = document.getElementById('progressFill') as HTMLDivElement;
        this.progressText = document.getElementById('progressText') as HTMLSpanElement;
        this.currentSegmentDiv = document.getElementById('currentSegment') as HTMLDivElement;
        this.termsList = document.getElementById('termsList') as HTMLDivElement;
        this.termCount = document.getElementById('termCount') as HTMLSpanElement;
        this.noTermsMessage = document.getElementById('noTermsMessage') as HTMLDivElement;
        this.addingProgress = document.getElementById('addingProgress') as HTMLDivElement;
        this.addingProgressText = document.getElementById('addingProgressText') as HTMLDivElement;
        this.addingProgressFill = document.getElementById('addingProgressFill') as HTMLDivElement;

        this.startBtn = document.getElementById('startBtn') as HTMLButtonElement;
        this.stopBtn = document.getElementById('stopBtn') as HTMLButtonElement;
        this.selectAllBtn = document.getElementById('selectAllBtn') as HTMLButtonElement;
        this.addSelectedBtn = document.getElementById('addSelectedBtn') as HTMLButtonElement;

        // 绑定事件监听器
        this.startBtn.addEventListener('click', () => {
            this.startExtraction();
        });

        this.stopBtn.addEventListener('click', () => {
            this.stopExtraction();
        });

        this.selectAllBtn.addEventListener('click', () => {
            this.selectAllTerms();
        });

        this.addSelectedBtn.addEventListener('click', () => {
            this.addSelectedTerms();
        });

        // 监听术语抽取相关的IPC事件
        this.electron.ipcRenderer.on('extraction-progress', (event: any, data: any) => {
            this.updateProgress(data.current, data.total, data.segment);
        });

        this.electron.ipcRenderer.on('term-extracted', (event: any, term: ExtractedTerm) => {
            this.addExtractedTerm(term);
        });

        this.electron.ipcRenderer.on('extraction-completed', (event: any, data: any) => {
            this.extractionCompleted();
        });

        this.electron.ipcRenderer.on('extraction-error', (event: any, error: string) => {
            this.showError(error);
        });

        this.electron.ipcRenderer.on('glossaries-received', (event: any, data: any) => {
            console.log('收到术语库数据:', data);
            this.setGlossaries(data.glossaries);
        });

        this.electron.ipcRenderer.on('terms-added-result', (event: any, result: any) => {
            console.log('术语添加结果:', result);
            this.hideAddingProgress();
            if (result.failed > 0) {
                this.showError(`术语添加完成：成功 ${result.success} 个，失败 ${result.failed} 个`);
            } else {
                this.showMessage(`成功添加 ${result.success} 个术语到术语库`);
            }
        });
    }

    setData(data: TermExtractionData): void {
        console.log('setData被调用，参数:', data);
        
        if (!data) {
            console.error('setData收到空数据');
            return;
        }
        
        this.projectId = data.projectId;
        this.projectName = data.projectName;
        this.srcLang = data.srcLang;
        this.tgtLang = data.tgtLang;

        console.log('设置UI元素...');
        this.projectNameSpan.textContent = data.projectName;
        this.languagePairSpan.textContent = `${data.srcLang} → ${data.tgtLang}`;
        console.log('UI元素设置完成');
    }

    loadGlossaries(): void {
        console.log('加载术语库...');
        this.electron.ipcRenderer.send('get-term-extraction-glossaries');
    }

    setGlossaries(glossaries: any[]): void {
        this.glossaries = glossaries;
        this.populateGlossarySelect();
    }

    populateGlossarySelect(): void {
        console.log('填充术语库下拉框，术语库数量:', this.glossaries.length);
        
        // 清空现有选项
        this.glossarySelect.innerHTML = '<option value="">请选择术语库...</option>';

        // 暂时显示所有术语库，后续可以根据需要添加语言对过滤
        this.glossaries.forEach(glossary => {
            const option = document.createElement('option');
            option.value = glossary.id;
            option.textContent = glossary.name;
            this.glossarySelect.appendChild(option);
            console.log('添加术语库选项:', glossary.name, 'ID:', glossary.id);
        });

        if (this.glossaries.length === 0) {
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '没有可用的术语库';
            option.disabled = true;
            this.glossarySelect.appendChild(option);
        }
    }

    startExtraction(): void {
        if (!this.glossarySelect.value) {
            this.electron.ipcRenderer.send('show-message', {
                type: 'warning',
                message: '请先选择一个术语库'
            });
            return;
        }

        this.isExtracting = true;
        this.extractionCancelled = false;
        this.extractedTerms = [];

        // 更新UI状态
        this.startBtn.classList.add('hidden');
        this.stopBtn.classList.remove('hidden');
        this.progressContainer.classList.remove('hidden');
        this.selectAllBtn.disabled = true;
        this.addSelectedBtn.disabled = true;
        this.glossarySelect.disabled = true;

        // 清空术语列表
        this.termsList.innerHTML = '';
        this.noTermsMessage.style.display = 'block';
        this.updateTermCount();

        // 发送抽取请求到主进程
        this.electron.ipcRenderer.send('start-term-extraction', {
            projectId: this.projectId,
            glossaryId: this.glossarySelect.value,
            srcLang: this.srcLang,
            tgtLang: this.tgtLang
        });
    }

    stopExtraction(): void {
        this.extractionCancelled = true;
        this.electron.ipcRenderer.send('stop-term-extraction', { projectId: this.projectId });
        this.extractionCompleted();
    }

    extractionCompleted(): void {
        this.isExtracting = false;

        // 更新UI状态
        this.startBtn.classList.remove('hidden');
        this.stopBtn.classList.add('hidden');
        this.progressContainer.classList.add('hidden');
        this.glossarySelect.disabled = false;

        if (this.extractedTerms.length > 0) {
            this.selectAllBtn.disabled = false;
            this.addSelectedBtn.disabled = false;
            this.noTermsMessage.style.display = 'none';
        }

        if (this.extractionCancelled) {
            this.showMessage('术语抽取已取消');
        } else {
            this.showMessage(`术语抽取完成，共找到 ${this.extractedTerms.length} 个唯一术语（已自动过滤重复项）`);
        }
    }

    updateProgress(current: number, total: number, segment: string): void {
        const percentage = Math.round((current / total) * 100);
        this.progressFill.style.width = `${percentage}%`;
        this.progressText.textContent = `${percentage}%`;
        this.currentSegmentDiv.textContent = `正在处理: ${segment.substring(0, 50)}...`;
    }

    addExtractedTerm(term: ExtractedTerm): void {
        this.extractedTerms.push(term);
        this.renderTermItem(term, this.extractedTerms.length - 1);
        this.updateTermCount();
        this.noTermsMessage.style.display = 'none';
        
        // 滚动到最新添加的术语
        this.termsList.scrollTop = this.termsList.scrollHeight;
    }

    renderTermItem(term: ExtractedTerm, index: number): void {
        const termItem = document.createElement('div');
        termItem.className = 'term-item';
        termItem.dataset.index = index.toString();

        termItem.innerHTML = `
            <input type="checkbox" class="term_checkbox" id="term_${index}">
            <div class="term_content">
                <div class="term-source">${this.escapeHtml(term.source)}</div>
                <div class="term-target">${this.escapeHtml(term.target)}</div>
                <div class="term-context">${this.escapeHtml(term.context)}</div>
            </div>
        `;

        // 添加点击事件来切换选择状态
        const checkbox = termItem.querySelector('.term_checkbox') as HTMLInputElement;
        termItem.addEventListener('click', (e: Event) => {
            if (e.target !== checkbox) {
                checkbox.checked = !checkbox.checked;
                this.updateTermItemSelection(termItem, checkbox.checked);
            }
        });

        checkbox.addEventListener('change', () => {
            this.updateTermItemSelection(termItem, checkbox.checked);
        });

        this.termsList.appendChild(termItem);
    }

    updateTermItemSelection(termItem: HTMLDivElement, selected: boolean): void {
        if (selected) {
            termItem.classList.add('selected');
        } else {
            termItem.classList.remove('selected');
        }
        this.updateAddSelectedButton();
    }

    updateTermCount(): void {
        this.termCount.textContent = `(${this.extractedTerms.length} 个术语)`;
    }

    updateAddSelectedButton(): void {
        const selectedTerms = this.getSelectedTerms();
        this.addSelectedBtn.disabled = selectedTerms.length === 0;
    }

    selectAllTerms(): void {
        const checkboxes = this.termsList.querySelectorAll('.term_checkbox') as NodeListOf<HTMLInputElement>;
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);

        checkboxes.forEach((checkbox, index) => {
            checkbox.checked = !allChecked;
            const termItem = checkbox.closest('.term-item') as HTMLDivElement;
            this.updateTermItemSelection(termItem, checkbox.checked);
        });

        this.selectAllBtn.textContent = allChecked ? '全选' : '取消全选';
    }

    getSelectedTerms(): ExtractedTerm[] {
        const selectedTerms: ExtractedTerm[] = [];
        const checkboxes = this.termsList.querySelectorAll('.term_checkbox') as NodeListOf<HTMLInputElement>;

        checkboxes.forEach((checkbox, index) => {
            if (checkbox.checked) {
                selectedTerms.push(this.extractedTerms[index]);
            }
        });

        return selectedTerms;
    }

    addSelectedTerms(): void {
        const selectedTerms = this.getSelectedTerms();
        if (selectedTerms.length === 0) {
            return;
        }

        this.electron.ipcRenderer.send('add-terms-to-glossary', {
            glossaryId: this.glossarySelect.value,
            terms: selectedTerms
        });

        // 显示添加进度
        this.showAddingProgress(selectedTerms.length);

        // 移除已添加的术语项
        const checkboxes = this.termsList.querySelectorAll('.term_checkbox') as NodeListOf<HTMLInputElement>;
        const itemsToRemove: HTMLDivElement[] = [];

        checkboxes.forEach((checkbox, index) => {
            if (checkbox.checked) {
                const termItem = checkbox.closest('.term-item') as HTMLDivElement;
                itemsToRemove.push(termItem);
            }
        });

        // 从数组中移除已添加的术语
        this.extractedTerms = this.extractedTerms.filter((_, index) => {
            const checkbox = checkboxes[index];
            return !checkbox.checked;
        });

        // 从DOM中移除元素
        itemsToRemove.forEach(item => item.remove());

        // 更新计数和按钮状态
        this.updateTermCount();
        this.updateAddSelectedButton();

        if (this.extractedTerms.length === 0) {
            this.noTermsMessage.textContent = '所有术语已添加到术语库';
            this.noTermsMessage.style.display = 'block';
            this.selectAllBtn.disabled = true;
        }
    }

    closeWindow(): void {
        if (this.isExtracting) {
            this.stopExtraction();
        }
        this.electron.ipcRenderer.send('close-term-extraction');
    }

    showMessage(message: string): void {
        this.electron.ipcRenderer.send('show-message', {
            type: 'info',
            message: message
        });
    }

    showError(error: string): void {
        this.electron.ipcRenderer.send('show-message', {
            type: 'error',
            message: error
        });
    }

    escapeHtml(text: string): string {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    showAddingProgress(totalTerms: number): void {
        this.addingProgress.classList.add('show');
        this.addingProgressText.textContent = `正在添加 ${totalTerms} 个术语到术语库...`;
        this.addingProgressFill.style.width = '0%';
        
        // 禁用相关按钮
        this.addSelectedBtn.disabled = true;
        this.selectAllBtn.disabled = true;
        this.startBtn.disabled = true;
        this.glossarySelect.disabled = true;
        
        // 模拟进度更新
        let progress = 0;
        const interval = setInterval(() => {
            progress += Math.random() * 15;
            if (progress > 90) progress = 90; // 不要到达100%，等待真实完成
            this.addingProgressFill.style.width = `${progress}%`;
        }, 300);
        
        // 存储interval以便后续清理
        (this.addingProgress as any)._interval = interval;
    }

    hideAddingProgress(): void {
        // 清理进度更新interval
        if ((this.addingProgress as any)._interval) {
            clearInterval((this.addingProgress as any)._interval);
            delete (this.addingProgress as any)._interval;
        }
        
        // 完成进度条
        this.addingProgressFill.style.width = '100%';
        
        // 延迟隐藏，让用户看到100%完成
        setTimeout(() => {
            this.addingProgress.classList.remove('show');
            
            // 重新启用按钮
            this.addSelectedBtn.disabled = false;
            this.selectAllBtn.disabled = false;
            this.startBtn.disabled = false;
            this.glossarySelect.disabled = false;
            
            // 更新按钮状态
            this.updateAddSelectedButton();
        }, 500);
    }
} 